#include "teacher.h"

using namespace Core;

Teacher::Teacher(QObject *parent) : QObject(parent)
{
    connect(&_timer, SIGNAL(timeout()), this, SLOT(showTask()));
    _timer.setInterval(60 * 1000);
}

Teacher::~Teacher()
{
    stop();
    hideTask();
}

void Teacher::registerProvider(ITaskProvider *provider)
{
    _providers[provider->name()] = provider;
}

void Teacher::start()
{
    _timer.start();
}

void Teacher::stop()
{
    _timer.stop();
}

void Teacher::enableProvider(const QString &providerName)
{
    if (!_enabledProviders.contains(providerName))
        _enabledProviders << providerName;
}

void Teacher::disableProvider(const QString &providerName)
{
    _enabledProviders.removeAll(providerName);
}

void Teacher::setInterval(int secInterval)
{
    _timer.setInterval(secInterval * 1000);
}

void Teacher::showTask()
{
    int randomProviderId = qrand() * _enabledProviders.count() / RAND_MAX;

    if (randomProviderId < 1)
    {
        emit logError("Cannot show task because there is no enabled providers");
        return;
    }

    if (!_providers.contains(_enabledProviders[randomProviderId]))
    {
        emit logError(QString("Cannot show task because provider '%1' was not found").arg(_enabledProviders[randomProviderId]));
        return;
    }

    ITaskProvider* provider = _providers[_enabledProviders[randomProviderId]];

    ITask* task = provider->getTask();

    if (task == NULL)
    {
        emit logError(QString("Cannot show task because provider '%1' have not returned task").arg(_enabledProviders[randomProviderId]));
        return;
    }

    _timer.stop();

    task->draw(_prepareTestingPanel(), this, SLOT(taskFinished(bool,int,QString)));
}

void Teacher::hideTask()
{
    _hideTestingPanel();
    _timer.start();
}

void Teacher::taskFinished(bool correct, int score, const QString problemsDecription)
{
    hideTask();

    emit taskFinished(correct, score, problemsDecription);
}

QWidget* Teacher::_prepareTestingPanel()
{
    _testingPanel.show();
    return _testingPanel.widget();
}

void Teacher::_hideTestingPanel()
{
    _testingPanel.hide();
}
